package utils

import (
	"bufio"
	"crypto/sha256"
	"encoding/hex"
	"github.com/Unknwon/goconfig"
	"gobindc_test/server/model"
	"log"
	"os"
	"strconv"
)

func GetConfig(confFilePath string) *model.DataConfig {
	cfg, err := goconfig.LoadConfigFile(confFilePath)
	if err != nil {
		log.Fatalf("无法加载配置文件： %s \n", err)
	}
	// 获取使用的端口
	serverPort, err := cfg.GetValue("DEFAULT", "server_port")
	if err != nil {
		log.Fatalln(err.Error())
	}
	// 获取队列的长度
	dataLength, err := cfg.GetValue("DEFAULT", "data_len")
	if err != nil {
		log.Fatalln(err.Error())
	}
	// 获取内存模式or硬盘模式
	dataSeat, err := cfg.GetValue("DEFAULT", "data_seat")
	if err != nil {
		log.Fatalln(err.Error())
	}
	dataDiskFile, err := cfg.GetValue("DEFAULT", "data_disk_file")
	if err != nil {
		log.Fatalln(err)
	}
	password, err := cfg.GetValue("DEFAULT", "password")
	if err != nil {
		log.Fatalln(err)
	}
	serverIP, err := cfg.GetValue("DEFAULT", "server_ip")
	if err != nil {
		log.Fatalln(err)
	}
	serverDeal, err := cfg.GetValue("DEFAULT", "server_deal")
	if err != nil {
		log.Fatalln(err)
	}
	port, err := strconv.Atoi(serverPort)
	if err != nil {
		log.Fatalln(err.Error())
	}
	length, err := strconv.Atoi(dataLength)
	if err != nil {
		log.Fatalln(err.Error())
	}
	hash := sha256.New()
	hash.Write([]byte(password))
	sum := hash.Sum(nil)
	password = hex.EncodeToString(sum)
	config := model.DataConfig{
		ServerPort:   port,
		DataLength:   length,
		DataSeat:     dataSeat,
		DataDiskFile: dataDiskFile,
		Password:     password,
		ServerIP:     serverIP,
		ServerDeal:   serverDeal,
	}
	return &config
}

func GetFileLine(filePath string) int {
	file, err := os.Open(filePath)
	if err != nil {
		create, err := os.Create(filePath)
		if err != nil {
			log.Fatalln(err.Error())
		}
		defer func(create *os.File) {
			err := create.Close()
			if err != nil {
				log.Fatalln(err.Error())
			}
		}(create)
		return 0
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			log.Fatalln(err.Error())
		}
	}(file)
	fd := bufio.NewReader(file)
	count := 0
	for {
		_, err := fd.ReadString('\n')
		if err != nil {
			break
		}
		count++
	}
	return count
}
